package com.boom.monitor.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.boom.common.annotation.Log;
import com.boom.common.core.controller.BaseController;
import com.boom.common.core.domain.AjaxResult;
import com.boom.common.core.page.TableDataInfo;
import com.boom.common.enums.BusinessType;
import com.boom.monitor.domain.MonitorTopology;
import com.boom.monitor.service.MonitorTopologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 拓扑管理Controller
 *
 * @author boom
 * @date 2021-06-15
 */
@RestController
@RequestMapping("/monitor/topology")
public class MonitorTopologyController extends BaseController {

	@Autowired
	private MonitorTopologyService monitorTopologyService;

	/**
	 * 查询拓扑管理列表
	 */
	@PreAuthorize("@ss.hasPermi('monitor:topology:list')")
	@GetMapping("/list")
	public TableDataInfo list(MonitorTopology monitorTopology) {
		startPage();
		List<MonitorTopology> list = monitorTopologyService.selectMonitorTopologyList(monitorTopology);
		return getDataTable(list);
	}

	/**
	 * 获取拓扑管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('monitor:topology:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") String id) {
		return AjaxResult.success(monitorTopologyService.selectMonitorTopologyById(id));
	}

	/**
	 * 新增拓扑管理
	 */
	@PreAuthorize("@ss.hasPermi('monitor:topology:add')")
	@Log(title = "拓扑管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody MonitorTopology monitorTopology) {
		int rows = monitorTopologyService.insertMonitorTopology(monitorTopology);
		return rows > 0 ? AjaxResult.success(monitorTopology.getId()) : AjaxResult.error();
	}

	/**
	 * 修改拓扑管理
	 */
	@PreAuthorize("@ss.hasPermi('monitor:topology:edit')")
	@Log(title = "拓扑管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody MonitorTopology monitorTopology) {
		return toAjax(monitorTopologyService.updateMonitorTopology(monitorTopology));
	}

	/**
	 * 删除拓扑管理
	 */
	@PreAuthorize("@ss.hasPermi('monitor:topology:remove')")
	@Log(title = "拓扑管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable String[] ids) {
		return toAjax(monitorTopologyService.deleteMonitorTopologyByIds(ids));
	}

	/**
	 * 上传到图片并且转为base64
	 *
	 * @param file 文件
	 */
	@PostMapping("/uploadToBase64")
	public String uploadToBase64(MultipartFile file) {
		if (file == null || file.isEmpty()) {
			throw new RuntimeException("图片不能为空！");
		}
		String contentType = file.getContentType();
		byte[] imageBytes = null;
		String base64EncoderImg = "";
		try {
			imageBytes = file.getBytes();
			BASE64Encoder base64Encoder = new BASE64Encoder();
			/*
			  1.Java使用BASE64Encoder 需要添加图片头（"data:" + contentType + ";base64,"），
			    其中contentType是文件的内容格式。
			  2.Java中在使用BASE64Enconder().encode()会出现字符串换行问题，这是因为RFC 822中规定，
			    每72个字符中加一个换行符号，这样会造成在使用base64字符串时出现问题，
			    所以我们在使用时要先用replaceAll("[\\s*\t\n\r]", "")解决换行的问题。
			 */
			base64EncoderImg = "data:" + contentType + "," + base64Encoder.encode(imageBytes);
			base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64EncoderImg;
	}


	/**
	 * 上传xml
	 *
	 * @param file 文件
	 * @return {@link String }
	 * @author yzw
	 * @date 2021-06-19
	 */
	@PostMapping("/uploadXml")
	public String uploadXml(MultipartFile file) {
		if (file == null || file.isEmpty()) {
			throw new RuntimeException("文件不能为空！");
		}
		try {
			InputStream is = file.getInputStream();
			String result = IoUtil.readUtf8(is);
			String remark = "<mxGraphModel";
			if (StrUtil.isNotBlank(result) && result.startsWith(remark)) {
				return result;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
